'use strict';

async function createTestData() {
  try {
    console.log('开始创建测试数据...');
    
    // 使用Sequelize连接数据库
    const { Sequelize } = require('sequelize');
    
    const dbConfig = {
      host: process.env.MySqlHost || '127.0.0.1',
      port: process.env.MySqlPort || 3306,
      user: process.env.MySqlUsername || 'root',
      password: process.env.MySqlPassword || '302108jw302',
    };
    
    const dbName = process.env.MySqlDatabase || 'wardrobe_db';
    
    const sequelize = new Sequelize(dbName, dbConfig.user, dbConfig.password, {
      host: dbConfig.host,
      port: dbConfig.port,
      dialect: 'mysql',
      logging: false,
      define: {
        raw: true,
        underscored: true,
        charset: 'utf8mb4',
        timestamps: true,
        paranoid: true,
        freezeTableName: true,
        createdAt: 'created_at',
        updatedAt: 'updated_at',
        deletedAt: 'deleted_at',
      },
      dialectOptions: {
        dateStrings: true,
        typeCast: true,
        charset: 'utf8mb4',
        collate: 'utf8mb4_unicode_ci',
      },
      timezone: '+08:00',
    });
    
    // 测试连接
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 1. 创建分类数据
    console.log('创建分类数据...');
    const categories = [
      { name: '上装', name_en: 'tops', level: 1, sort_order: 1, is_active: true },
      { name: '下装', name_en: 'bottoms', level: 1, sort_order: 2, is_active: true },
      { name: '外套', name_en: 'outerwear', level: 1, sort_order: 3, is_active: true },
      { name: '鞋子', name_en: 'shoes', level: 1, sort_order: 4, is_active: true },
      { name: '配饰', name_en: 'accessories', level: 1, sort_order: 5, is_active: true },
    ];
    
    for (const category of categories) {
      await sequelize.query(
        `INSERT IGNORE INTO categories (name, name_en, level, sort_order, is_active, created_at, updated_at) 
         VALUES (?, ?, ?, ?, ?, NOW(), NOW())`,
        { replacements: [category.name, category.name_en, category.level, category.sort_order, category.is_active] }
      );
    }
    
    // 2. 创建标签数据
    console.log('创建标签数据...');
    const tags = [
      { name: '休闲', type: 'style', color: '#409EFF' },
      { name: '正式', type: 'style', color: '#67C23A' },
      { name: '运动', type: 'style', color: '#E6A23C' },
      { name: '春季', type: 'season', color: '#67C23A' },
      { name: '夏季', type: 'season', color: '#F56C6C' },
      { name: '秋季', type: 'season', color: '#E6A23C' },
      { name: '冬季', type: 'season', color: '#909399' },
    ];
    
    for (const tag of tags) {
      await sequelize.query(
        `INSERT IGNORE INTO tags (name, type, color, is_active, created_at, updated_at) 
         VALUES (?, ?, ?, ?, NOW(), NOW())`,
        { replacements: [tag.name, tag.type, tag.color, true] }
      );
    }
    
    // 3. 获取用户ID
    const [users] = await sequelize.query('SELECT id FROM users WHERE username = "demo" LIMIT 1');
    if (users.length === 0) {
      console.log('演示用户不存在，请先创建演示用户');
      await sequelize.close();
      return;
    }
    const userId = users[0].id;
    
    // 4. 创建一些测试衣服数据
    console.log('创建测试衣服数据...');
    const [categories_result] = await sequelize.query('SELECT id, name FROM categories');
    const categoryMap = {};
    categories_result.forEach(cat => {
      categoryMap[cat.name] = cat.id;
    });
    
    const testClothes = [
      {
        name: '白色T恤',
        category_id: categoryMap['上装'],
        color: '白色',
        color_hex: '#FFFFFF',
        brand: 'Uniqlo',
        season: 'summer',
        style: 'casual',
        status: 'available',
        price: 99.00,
        purchase_date: '2024-01-15',
        notes: '基础款白T恤，百搭'
      },
      {
        name: '牛仔裤',
        category_id: categoryMap['下装'],
        color: '蓝色',
        color_hex: '#4169E1',
        brand: 'Levi\'s',
        season: 'all',
        style: 'casual',
        status: 'available',
        price: 299.00,
        purchase_date: '2024-02-01',
        notes: '经典牛仔裤'
      },
      {
        name: '黑色西装外套',
        category_id: categoryMap['外套'],
        color: '黑色',
        color_hex: '#000000',
        brand: 'ZARA',
        season: 'autumn',
        style: 'formal',
        status: 'available',
        price: 599.00,
        purchase_date: '2024-03-10',
        notes: '商务正装'
      }
    ];
    
    for (const clothing of testClothes) {
      await sequelize.query(
        `INSERT INTO clothing (user_id, name, category_id, color, color_hex, brand, season, style, status, price, purchase_date, notes, is_favorite, created_at, updated_at) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
        { 
          replacements: [
            userId, clothing.name, clothing.category_id, clothing.color, clothing.color_hex,
            clothing.brand, clothing.season, clothing.style, clothing.status, clothing.price,
            clothing.purchase_date, clothing.notes, false
          ] 
        }
      );
    }
    
    await sequelize.close();
    console.log('测试数据创建完成！');
    console.log('- 创建了5个分类');
    console.log('- 创建了7个标签');
    console.log('- 创建了3件测试衣服');
    
  } catch (error) {
    console.error('创建测试数据失败:', error);
    process.exit(1);
  }
}

// 如果直接运行此文件
if (require.main === module) {
  createTestData();
}

module.exports = createTestData;
